/**
 * 相关案例的页面的逻辑处理
 * Created by Administrator on 2016/12/29.
 */

module.exports = function ($scope, $state, caseBarDetailAnLiService, $anchorScroll, $location, $cookies,$rootScope,$stateParams) {
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + 1);

    //取出当前案件的ID
   var caseId=$cookies.get('caseAppId');

    /*登录ID*/
    $scope.loginId = kbt.decrypt($cookies.get('cookieUserId'));
    $scope.caseName = $cookies.get('caseAppName');

   //定义一个全局的页码
    var detailspagination=0;

    //设置总页码
    var sumpaging=0;

    var labelsrc = [];
    //条件字符串

    var objstr = "searchWord:" + $scope.caseName;


  /**数组列表*/
  var casejsonlist=[];

    // 相关案例列表
    $scope.CorrelationCabe = function (index, pagesize, conditions,caseId) {
        $rootScope.loadingShow = true;
        $rootScope.fadeShow = true;
        caseBarDetailAnLiService.RefuseMsg(index, pagesize, conditions,caseId).then(function (data) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            var data1 = JSON.parse(data.data); //数据不规范所以要转一下对象
            $scope.CabeMyshow=false;
            if(data1.searchResult.judgements.length!=0){
                $scope.CabeMyshow=true;
            }
             sumpaging=data1.searchResult.totalCount
            setlistcase(data1);
            menuset(data1.menu);
            //设置分页
            setPage(data1.searchResult);

        }, function (response) {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
            console.error('updatemessage error', response.status, response.statusText);
        });
    };

    $scope.init = function () {
        $scope.CorrelationCabe("0", "10", objstr,caseId);
        /*用于固定导航条*/
        sessionStorage.navNum = 5;
    };
    $scope.init();
    // 增加标签
    $scope.rejectMsg = function (name, Country, str) {
        addByValue(labelsrc, name, Country);
        setcondition(labelsrc, str);
        $scope.CorrelationCabe("0", "10", objstr,caseId);
        $scope.records = labelsrc;
        $scope.$apply();//需要手动刷新
    };

    //去除标签
    $scope.rejectMsg3 = function ($index) {
      labelsrc.splice($index, 1);
        //搜索刷新页面
        var list = objstr.split("!%!");
        list.splice($index+1,1);
        var newObjstr = list[0];
        for(var i=1;i<list.length;i++) {
          newObjstr += "!%!" + list[i];
        }
        objstr = newObjstr;
        $scope.CorrelationCabe("0", "10", objstr,caseId);
        $scope.records = labelsrc;

    };

    //判断这个层级是否有标签如果有就把这个标签去掉
    function addByValue(arr, name, country) {
        var stc = false;
        var i2 = 0;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].Name + arr[i].Country === name + country) {
                stc = true;
                i2 = i;
                break;
            }
        }
        if (stc) {
            //条件存在
            // labelsrc.splice(i2, 1);

            // location.reload();
        } else {
            labelsrc.push({
                "Name": name,
                "Country": country
            }); // 添加到最后
        }
    }

    //拼接条件
    function setcondition(labelsrc,str) {
      objstr += "!%!filters=" + str;
    }

    /* 列表处理*/
    function setlistcase(data1) {
        var table = "";
        var searchresult = data1.searchResult

        var casejson = JSON.stringify(searchresult.judgements);

        casejsonlist=JSON.parse(casejson);
        $scope.correlation =casejsonlist

    }

    /**处理左侧列表*/
    function menuset(datameun) {

        // datameun
        //案由
        var menuCause = new Object();
        menuCause.name = "按案由";
        menuCause.childs = datameun.menuCause;

        //按地域
        var menuPca = new Object();
        menuPca.name = "按地域";
        menuPca.childs = datameun.menuPca;

        //按法院层级
        var menuJudgement = new Object();
        menuJudgement.name = "按法院层级";
        menuJudgement.childs = datameun.menuJudgement;

        //按年份
        var menuYear = new Object();
        menuYear.name = "按年份";
        menuYear.childs = datameun.menuYear;

        //按审理程序
        var menuCaseBusiness = new Object();
        menuCaseBusiness.name = "按审理程序";
        menuCaseBusiness.childs = datameun.menuCaseBusiness;

        //按文书性质
        var menuLegalInstrumentType = new Object();
        menuLegalInstrumentType.name = "按文书性质";
        menuLegalInstrumentType.childs = datameun.menuLegalInstrumentType;

        var setting = {
            data: {
                key: {
                    children: "childs",
                }
            },
            callback: {
                onClick: zTreeOnClick
            },
            view: {
                showLine: false
            }
        };
        var zNodes = [menuCause, menuPca,menuYear,menuCaseBusiness,menuLegalInstrumentType];

        $(document).ready(function () {
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        });
        function zTreeOnClick(event, treeId, treeNode) {
            if (treeNode.level !== 0) {
                var val = formatCondition(treeNode.getPath()[0].name);
                $scope.rejectMsg(val, treeNode.name, val + '_'+ (treeNode.getPath().length - 2) + '_' + treeNode.name);
            }
        };
    }

    //格式化引用法规
    $scope.formatLaws = function (laws) {
      if(laws && laws != null && laws != "") {
        var array = laws.split("\r\n");
        return array;
      } else {
        return null;
      }
    };

    function formatCondition(key) {
      return {
        "按案由":"案由",
        "按地域":"地域",
        "按年份":"年份",
        "按审理程序":"审理程序",
        "按文书性质":"文书性质",
        "按关键字":"关键字",
        "按法院层级":"法院层级"
      }[key];
    }

    var GeneralPage=0;
    //分页
    //请求完成后设置分页
    function setPage(data) {
        var index=data.index;

       // 每一页显示的数量
        var EachSize=10;

        //总条数
        var PageSize=data.totalCount;

        //分页的数组
        $scope.Pagelist = [];

        //向上取整得到总页数
      GeneralPage= Math.ceil(data.totalCount/EachSize);


      $scope.GeneralPage=GeneralPage;

       var indexpage=data.index+1;

        // console.log(Math.ceil(6/EachSize),"----------------",data.totalCount);

        if(GeneralPage + 1>11){
            if(indexpage>5){
                var yema=indexpage-4;
                var zuihouyema=yema+10;
                if(indexpage<GeneralPage-5){
                    for(var i=yema;i<zuihouyema;i++){
                        $scope.Pagelist.push(i);
                    }
                }else {
                    // var yemaa=GeneralPage-9;
                    for(var i=yema;i<GeneralPage+1;i++){
                        $scope.Pagelist.push(i);
                    }
                }

            }else{
                for(var i=1;i<11;i++){
                    $scope.Pagelist.push(i);
                }
            }
        }else {
            //取到分页数组
            for (var i = 1; i < GeneralPage + 1; i++) {
                $scope.Pagelist.push(i);
            }
        }


        $('.select').css('color', '#666');
        $scope.totalPage = data.pagesize;
        $scope.totalCount = PageSize; //总条数 已经ok
        $scope.totalPas =  $scope.Pagelist;         //分页需要的数组
        $scope.page = indexpage;   //当前页

        setTimeout(function () {
            if ($scope.page === 0) {
                $('.select' + ($scope.page + 1)).css('color', 'red');
            } else {
                $('.select' + ($scope.page)).css('color', 'red');
            }

        }, 50);
    }

    /*用户点击分页点击改变页码*/
    $scope.changePage = function (currentPage) {
        if (currentPage <= GeneralPage && currentPage > -1) {

            // totalPage 页码
            $scope.CorrelationCabe(currentPage-1, "10", objstr,caseId);

            //用户改变页码的时候保存下当前页面的下标
            detailspagination=currentPage-1;

            $anchorScroll.yOffset = 500;// 总是滚动额外的50像素
            // 将location.hash的值设置为
            // 你想要滚动到的元素的id
            $location.hash('ybcabelist');
            // 调用 $anchorScroll()
            $anchorScroll();

        } else {
            console.log('列表页码越界!');
        }
    }



    // 收藏 和取消收藏
    $scope.Enshrine = function (relatedId,relatiedInfo,flot,index,mtitle) {
        $scope.relatedStatus="3";
        //看是否是关注还是取消
        if(flot){
            $scope.relatedStatus="0";
        }else {
            $scope.relatedStatus="1";
        }
        //相关案例ID 当前案件ID 取消和关注 整个案件的内容  userId：用户id，relatedName：相关案例名称
        caseBarDetailAnLiService.Enshrine(relatedId, caseId,  $scope.relatedStatus,relatiedInfo, $scope.loginId,mtitle).then(function (data) {
            if(data.code==1){
                if(flot){
                    casejsonlist[index].concern=false;
                }else{
                    casejsonlist[index].concern=true;
                }
                $scope.correlation =casejsonlist
            }else {

            }
        }, function (response) {
            console.error('updatemessage error', response.status, response.statusText);
        });


    };


    //跳转详情
    $scope.gocaseBarDeailAnliDetailController = function (downloadid,pagination,pagefloast,title) {
        pagination=detailspagination*10+pagination

        $state.go("caseBarDetailAnLiDetail");

        $cookies.put('Condition', objstr, {
            expires: expireDate
        });

   /*     $cookies.put('location', location, {
            expires: expireDate
        });*/
        $cookies.put('pagination', pagination, {
            expires: expireDate
        });
        $cookies.put('sumpaging', sumpaging, {
            expires: expireDate
        });
        $cookies.put('downloadid', downloadid, {
            expires: expireDate
        });
        $cookies.put('mCaseheadline', title, {
            expires: expireDate
        });
    };


}
